package cn.buk.tms.vas.service;

import cn.buk.api.vaas.dto.BaseResponse;
import cn.buk.api.vaas.dto.VasOrderCreateResponse;
import cn.buk.api.vaas.dto.VasOrderFlightDto;
import cn.buk.api.vaas.dto.VasOrderResponse;
import cn.buk.api.vaas.service.AirportService;
import cn.buk.common.JsonResult;
import cn.buk.common.dto.CommonDto;
import cn.buk.common.flight.dto.FlightBasicInfo;
import cn.buk.common.flight.dto.FlightInfoDto;
import cn.buk.qms.SmsUtil;
import cn.buk.tms.dao.FlightOrderDao;
import cn.buk.tms.dao.ProductDao;
import cn.buk.tms.entity.config.EnterpriseConfig;
import cn.buk.tms.entity.order.OrderNoInfo;
import cn.buk.tms.sc.SearchFlightOrderCriteria;
import cn.buk.qms.service.BaseOrderService;
import cn.buk.tms.common.constant.TmsOrderConstant;
import cn.buk.tms.common.dto.base.BaseOrderDto;
import cn.buk.tms.entity.bill.BillInfo;
import cn.buk.tms.entity.misc.*;
import cn.buk.tms.entity.order.flight.FlightOrder;
import cn.buk.tms.entity.order.flight.FlightOrderFlight;
import cn.buk.tms.entity.order.vas.VasOrder;
import cn.buk.tms.entity.order.vas.VasOrderFlight;
import cn.buk.tms.entity.order.vas.VasOrderPassenger;
import cn.buk.tms.vas.dto.VasOrderPassengerDto;
import cn.buk.tms.vas.dto.request.VasOrderRequestDto;
import cn.buk.tms.vas.dto.response.VasOrderResponseDto;
import cn.buk.common.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static cn.buk.tms.common.constant.TmsOrderConstant.ORDER_TYPE_FLIGHT;
import static cn.buk.tms.common.constant.TmsOrderConstant.PRODUCT_TYPE_VAAS;

/**
 * @author yfdai
 */
@Component
public class VasOrderServiceImpl extends BaseOrderService implements VasOrderService {

    @Autowired
    private FlightOrderDao flightOrderDao;

    @Autowired
    private ProductDao productDao;


    @Override
    public JsonResult createVasOrder(final int enterpriseId, final String operator, VasOrderRequestDto dto) {
        if (dto == null || dto.getProductCode().length() == 0
            || dto.getProductName().length() == 0) {
            return JsonResult.createJsonResult(-1, "产品代码、产品名称是必需的。");
        }

        if (dto.getCustomerId() < 0) {
            return JsonResult.createJsonResult(-2, "请选择客户");
        }

        Customer customer = null;
        if (dto.getCustomerId() > 0) {
            customer = customerDao.getCustomerById(dto.getCustomerId());
            if (customer == null || customer.getEnterpriseId() != enterpriseId) {
                return JsonResult.createJsonResult(-3, "该客户不存在");
            }
        }

        if (dto.getPassengers().isEmpty()) {
            return JsonResult.createJsonResult(-4, "需要填写客人信息");
        }

        for (VasOrderPassengerDto psgDto : dto.getPassengers()) {
          psgDto.setId(0);
            if (psgDto.getName().length() < 2) {
                return JsonResult.createJsonResult(-5, "需要填写客人的名字");
            }
        }

        if (VasOrder.VAS_ORDER_TYPE_VAAS == dto.getOrderType()) {
          if (dto.getSupplierId() < 1) {
            return JsonResult.createJsonResult(-7, "供应商");
          }
          if (dto.getPaymentMethodId() < 1) {
            return JsonResult.createJsonResult(-8, "付款方式");
          }
        }

        var serviceProduct = productDao.getTieInProductByCode(enterpriseId, dto.getProductCode());
        if (serviceProduct == null && dto.getOrderType() == VasOrder.VAS_ORDER_TYPE_LOCAL) {
            return JsonResult.createJsonResult(-6, "未找到对应的服务产品信息");
        }

        return doCreateVasOrder(enterpriseId, operator, dto, customer, serviceProduct);
    }

    private JsonResult doCreateVasOrder(final int enterpriseId, final String operator, VasOrderRequestDto dto, Customer customer, TieInProduct serviceProduct) {
      final int productType = dto.getOrderType() == VasOrder.VAS_ORDER_TYPE_LOCAL ? serviceProduct.getProductType()
          : TieInProduct.THIRD_VAS_PRODUCT;

      VasOrder info = new VasOrder();
      BeanUtils.copyProperties(dto, info);

      //产品类型
      info.setProductType(productType);

      info.setCreateDate(DateUtil.getCurDate());
      info.setOperator(operator);
      info.setEnterpriseId(enterpriseId);

      if (productType == TieInProduct.INSURANCE) {
        // 保险
        info.setOrderNo(
            orderNoGenerator.generateOrderNo(enterpriseId, OrderNoInfo.ORDER_INSURANCE));
      } else {
        // 其它vas订单
        info.setOrderNo(orderNoGenerator.generateOrderNo(enterpriseId, OrderNoInfo.ORDER_VAS));
      }

      if (dto.getCustomerId() == 0) {
        //散客
        info.setCustomerType(0);
      } else {
        info.setCustomerType(1);
        info.setCustomer(customer);
      }

      info.setPassengers(null);
      for (VasOrderPassengerDto psgDto : dto.getPassengers()) {
        VasOrderPassenger psg = new VasOrderPassenger();
        BeanUtils.copyProperties(psgDto, psg);

        psg.setEnterpriseId(enterpriseId);
        psg.setOrder(info);
        psg.setId(0);

        info.getPassengers().add(psg);
      }

      info.setFlights(null);
      if (dto.getFlights().size() > 0) {
        for (FlightInfoDto flt : dto.getFlights()) {
          VasOrderFlight vasOrderFlight = new VasOrderFlight();
          vasOrderFlight.setOrder(info);
          vasOrderFlight.setEnterpriseId(enterpriseId);
          vasOrderFlight.setId(0);

          BeanUtils.copyProperties(flt, vasOrderFlight.getFlight());

          vasOrderFlight.getFlight().setDepartureDate(DateUtil.formatDate(flt.getDdate(), "yyyy-MM-dd"));


          info.getFlights().add(vasOrderFlight);
        }
      }

      if (info.getOrderType() == VasOrder.VAS_ORDER_TYPE_VAAS && info.getFlights().size() != 1) {
        return JsonResult.createJsonResult(-7, "机场服务订单目前仅支持单程服务订单");
      }

      if (dto.getSupplierId() > 0) {
        Supplier supplier = new Supplier();
        supplier.setId(dto.getSupplierId());
        info.setSupplier(supplier);
      }

      if (dto.getPaymentMethodId() > 0) {
        PaymentMethod pm = new PaymentMethod();
        pm.setId(dto.getPaymentMethodId());

        info.setPaymentMethod(pm);
      }

      int retCode = vasOrderDao.createVasOrder(info);

      return JsonResult.createJsonResult(retCode);
    }

    /**
     * 获取 vas订单详情
     */
    @Override
    public VasOrderResponseDto getVasOrderById(int enterpriseId, int userId, int id) {
      VasOrder o = vasOrderDao.getOrderById(id);
      if (o == null || o.getEnterpriseId() != enterpriseId) {
        return null;
      }

      List<Integer> allowedCustomerIds = searchAllowedCustomerIds(enterpriseId, userId);
      if (allowedCustomerIds.size() > 0 && o.getCustomer() != null) {
        if (!allowedCustomerIds.contains(o.getCustomer().getId())) {
          return null;
        }
      }

      //是否要对当前用户隐藏客户名称
      if (isNeedHideCustomerName(enterpriseId, userId)) {
        User user = userDao.getUserById(userId);
        maskCustomerName(o.getCustomer(), o.getOperator(), user.getUsername(), true);
      }

      cleanVasOrder(o);

      VasOrderResponseDto dto = VasOrderResponseDto.createByVasOrder(o);
      searchVasOrderFlights(dto);

      //处理机场中文名
      for(FlightBasicInfo flt: dto.getFlights()) {
        processAirportName(flt);
      }

      if (dto.getBlanketOrderId() != null && dto.getBlanketOrderId() > 0) {
        //获取上级订单或子订单
        BlanketOrder parentOrder = flightOrderDao.searchParentOrder(enterpriseId, dto.getBlanketOrderId());
        if (parentOrder != null) {
          if (parentOrder.getActualOrderType() == ORDER_TYPE_FLIGHT) {
            FlightOrder flightOrder = flightOrderDao.getOrderDetailById(parentOrder.getActualOrderId());

            BaseOrderDto baseOrderDto = new BaseOrderDto();
            baseOrderDto.setId(flightOrder.getId());
            baseOrderDto.setOrderType(ORDER_TYPE_FLIGHT);
            baseOrderDto.setOrderNo(flightOrder.getOrderNo());
            baseOrderDto.setOrderStatus(flightOrder.getStatus());

            dto.setParentOrder(baseOrderDto);
          }
        }
      }

      return dto;
    }

    private void processAirportName(FlightBasicInfo flt) {
      if (flt.getDportName() == null) {
        flt.setDportName(getAirportName(flt.getDport()));
      }
      if (flt.getAportName() == null) {
        flt.setAportName(getAirportName(flt.getAport()));
      }
    }

    /**
     * 目前vasOrder中还没有保存航班信息，所以需要从关联的机票订单中查找
     */
    private void searchVasOrderFlights(VasOrderResponseDto o) {
      if (o.getFlights().size() > 0) {
//        logger.info("searchVasOrderFlights: " + o.getFlights().size());
        return;
      }

      if (o.getFlightOrderId() > 0) {
        // 获取航班信息
        List<FlightOrderFlight> flights = flightOrderDao
                .searchFlightOrderFlights(o.getFlightOrderId());
//        logger.info("searchVasOrderFlights: " + flights.size());
        for (FlightOrderFlight flight0 : flights) {
          flight0.setOrder(null);

          FlightBasicInfo flight1 = new FlightBasicInfo();
          BeanUtils.copyProperties(flight0.getFlight(), flight1);

          try {
            flight1.setDdate(DateUtil.convertToDate(flight0.getFlight().getDdate()));
          } catch (ParseException ignored) {
          }

          o.getFlights().add(flight1);
        }
      }
    }

    /**
     * 查找vas订单
     *
     * @param enterpriseId 当前企业id
     * @param username 当前用户名
     * @param sc 查找条件
     * @return 服务订单列表
     */
    @Override
    public List<VasOrderResponseDto> searchVasOrders(int enterpriseId, final int userId, final String username,
        SearchFlightOrderCriteria sc) {
      User user = userDao.getUserByUsername(username, enterpriseId);
      List<Integer> allowedCustomerIds = searchAllowedCustomerIds(enterpriseId, userId);

      Set<String> roles = userDao.loadUserRoles(user.getId());
      final boolean isAdmin = roles.contains(RoleInfo.ROLE_ADMIN);

      if (isOnlySeeOwn(enterpriseId, userId)) {
        //仅能查看自己的订单
        sc.setOp1(user.getUsername());
      }

      List<VasOrder> orders = vasOrderDao.searchVasOrders(enterpriseId, username, sc, isAdmin, allowedCustomerIds);
      final boolean needHideCustomerName = isNeedHideCustomerName(enterpriseId, userId);
      for (VasOrder order : orders) {
        maskCustomerName(order.getCustomer(), order.getOperator(), user.getUsername(), needHideCustomerName);
      }

      return convertToVasOrderDto(orders);
    }

  @Override
  public CommonDto<VasOrderResponseDto> searchVasOrders2(int enterpriseId, int userId, String username, SearchFlightOrderCriteria sc) {
    List<VasOrderResponseDto> datas = this.searchVasOrders(enterpriseId, userId, username, sc);

    CommonDto<VasOrderResponseDto> commonDto = new CommonDto<>();
    commonDto.setDataList(datas);
    commonDto.setPage(sc.getPage());

    return commonDto;
  }

  private List<VasOrderResponseDto> convertToVasOrderDto(List<VasOrder> orders) {
      cleanVasOrders(orders);

      List<VasOrderResponseDto> dtos = new ArrayList<>();
      for (VasOrder order : orders) {
        VasOrderResponseDto dto = VasOrderResponseDto.createByVasOrder(order);
        searchVasOrderFlights(dto);

        dtos.add(dto);

        //处理机场中文名
        for(FlightBasicInfo flt: dto.getFlights()) {
          processAirportName(flt);
        }
      }

      return dtos;
    }

    @Override
    public List<VasOrderResponseDto> searchInsuranceOrders(int enterpriseId, int userId, SearchFlightOrderCriteria sc) {
      List<Integer> allowedCustomerIds = searchAllowedCustomerIds(enterpriseId, userId);

      if (isOnlySeeOwn(enterpriseId, userId)) {
        //仅能查看自己的订单
        User user = userDao.getUserById(userId);
        sc.setOp1(user.getUsername());
      }

      List<VasOrder> orders = vasOrderDao.searchInsuranceOrders(enterpriseId, sc, allowedCustomerIds);

      final boolean needHideCustomerName = isNeedHideCustomerName(enterpriseId, userId);
      User user = userDao.getUserById(userId);
      for (VasOrder order : orders) {
        maskCustomerName(order.getCustomer(), order.getOperator(), user.getUsername(), needHideCustomerName);
      }

      return convertToVasOrderDto(orders);
    }


    private void cleanVasOrder(VasOrder vasOrder) {
        for (VasOrderPassenger psg : vasOrder.getPassengers()) {
            psg.setOrder(null);
        }

        for (VasOrderFlight flt : vasOrder.getFlights()) {
            flt.setOrder(null);
        }
    }

    private void cleanVasOrders(List<VasOrder> orders) {
        for (VasOrder vasOrder : orders) {
            cleanVasOrder(vasOrder);
        }
    }

    @Override
    public List<OperationLog> searchVasOrderHistory(int enterpriseId, int orderId) {
        return vasOrderDao.searchVasOrderHistory(enterpriseId, orderId);
    }

    /**
     * 修改备注
     */
    @Override
    public JsonResult updateVasOrderRemark(int enterpriseId, String username, int orderId,
        String remark) {
        int retCode = vasOrderDao.updateVasOrderRemark(enterpriseId, username, orderId, remark);
        return JsonResult.createJsonResult(retCode);
    }

    /**
     * 修改订单的供应商及支出支付方式
     *
     * @param enterpriseId 企业id
     * @param username 用户名
     * @param orderId 订单id
     * @param supplierId 供应商id
     * @param paymentMethodId 支出支付方式id
     */
    @Override
    public JsonResult updateVasOrderSupplier(final int enterpriseId, final String username,
        final int orderId, final int supplierId, final int paymentMethodId) {
        Supplier supplier = enterpriseDao.getSupplierById(enterpriseId, supplierId);
        if (supplier == null) {
            return JsonResult.createJsonResult(-1, "供应商不存在");
        }

        //支付方式
        PaymentMethod pm = enterpriseDao.getPaymentMethodById(enterpriseId, paymentMethodId);

        return JsonResult.createJsonResult(
            vasOrderDao.updateSupplier(enterpriseId, username, orderId, supplier, pm));
    }

    @Override
    public JsonResult cancelVasOrder(int enterpriseId, String username, int orderId, String remark) {

        VasOrder vasOrder = vasOrderDao.getOrderById(orderId);
        if (vasOrder == null || vasOrder.getEnterpriseId() != enterpriseId) {
            return JsonResult.createJsonResult(-1, "没有此订单");
        }

        if (vasOrder.getOrderType() == 1) {
            if (vasOrder.getExternalOrderNo() != null && vasOrder.getExternalOrderNo().trim().length() > 0) {
                //TODO 检查接口订单状态
                int retCode = cancelRemoteVaasOrder(enterpriseId, username, vasOrder, "人工取消订单");
                if (retCode != 0) {
                    return JsonResult.createJsonResult(-2, "已通过接口提交了订单");
                }
            }
        }

        return JsonResult
            .createJsonResult(vasOrderDao.cancelVasOrder(enterpriseId, username, orderId, remark));
    }



    @Override
    public JsonResult processVasOrder(final int enterpriseId, final String username, final int orderId) {
      //核对信用额度是否足够
      VasOrder orderInfo = vasOrderDao.getOrderById(orderId);
      if (orderInfo == null || orderInfo.getEnterpriseId() != enterpriseId) {
        return JsonResult.createJsonResult(-404, "不存在");
      }

      if (orderInfo.getCustomer() != null && orderInfo.getCustomer().getCustomerEnterpriseId() > 0) {
        //该客户可以判断授信额度
        final int customerEnterpriseId = orderInfo.getCustomer().getCustomerEnterpriseId();
        if (isOverCreditLimit(enterpriseId, customerEnterpriseId, orderInfo.getTotal())) {
          return JsonResult.createJsonResult(-100, "订单金额(" + orderInfo.getTotal() + ")大于可用额度");
        }
      }

      return JsonResult
              .createJsonResult(vasOrderDao.processVasOrder(enterpriseId, username, orderId, null));
    }

    @Override
    public JsonResult finishVasOrder(int enterpriseId, String username, int orderId,
        String remark) {

        VasOrder vasOrder = vasOrderDao.getOrderById(orderId);
        if (vasOrder == null || vasOrder.getEnterpriseId() != enterpriseId) {
            return JsonResult.createJsonResult(-1, "没有此订单");
        }

        if (vasOrder.getTicketer() == null || !vasOrder.getTicketer().equalsIgnoreCase(username)) {
            return JsonResult.createJsonResult(-3, "您不是该订单的处理人");
        }

        if (vasOrder.getSupplier() == null) {
            return JsonResult.createJsonResult(-4, "供应商不能为空");
        }

        if (vasOrder.getPaymentMethod() == null) {
            return JsonResult.createJsonResult(-5, "支付方式不能为空");
        }

        int retCode = vasOrderDao.finishVasOrder(enterpriseId, username, orderId, remark);
        if (retCode == 1) {
            //输出为账单
          importService.importVasOrder(enterpriseId, username, orderId);
        }

        return JsonResult.createJsonResult(retCode);
    }

    /**
     * 修改vasOrder中的客人信息
     */
    @Override
    public JsonResult updateVasOrderPassenger(int enterpriseId, String username, int orderId,
        int psgId, String psgName, String psgIdNo, String psgRemark) {
        int retCode = vasOrderDao
            .updateVasOrderPassenger(enterpriseId, username, orderId, psgId, psgName, psgIdNo,
                psgRemark);
        return JsonResult.createJsonResult(retCode);
    }

    /**
     * 修改vasOrder为已付款状态
     */
    @Override
    public JsonResult updateVasOrderPaid(int enterpriseId, String username, int orderId,
        String remark) {
        int retCode = vasOrderDao.updateVasOrderPaid(enterpriseId, username, orderId, remark);
        return JsonResult.createJsonResult(retCode);
    }

    @Override
    public JsonResult updateVasOrderPrice(int enterpriseId, String username, int orderId,
        double price, double discount, double cost) {
        int retCode = vasOrderDao
            .updateVasOrderPrice(enterpriseId, username, orderId, price, discount, cost);
        return JsonResult.createJsonResult(retCode);
    }

    @Override
    public JsonResult updateVasOrderPayment(int enterpriseId, String username, int orderId,
        int paymentMethodId) {
        PaymentMethod o = enterpriseDao.getPaymentMethodById(paymentMethodId);
        if (o == null || o.getEnterpriseId() != enterpriseId) {
            return JsonResult.createJsonResult(-1, "支付方式不存在");
        }

        int retCode = vasOrderDao.updatePaymentMethod(enterpriseId, username, orderId, o);

        return JsonResult.createJsonResult(retCode);
    }

    /**
     * 回滚服务单状态
     */
    @Override
    @Secured({RoleInfo.ROLE_ADMIN, RoleInfo.ROLE_SUPERVISOR})
    public JsonResult rollbackVasOrderStatus(final int enterpriseId, final String username,
        final int orderId, final String remark) {
        if (remark == null || remark.trim().length() < 2) {
            return JsonResult.createJsonResult(-10, "请输入理由");
        }

        // 检查是否有对应的账单，如果有，就不能回滚
        VasOrder vasOrder = vasOrderDao.getOrderById(orderId);
        if (vasOrder == null || vasOrder.getEnterpriseId() != enterpriseId) {
            return JsonResult.createJsonResult(-1, "数据错误");
        }

        List<BillInfo> billInfos = billService
            .searchBillInfoByOrderNo(enterpriseId, vasOrder.getOrderNo());
        if (billInfos.size() > 0) {
            doSendAlert(enterpriseId, "服务单(" + vasOrder.getOrderNo() + ")回滚失败，存在对应的账单", null,
                EntDepartment.DEPT_ADMINISTRATOR);
            return JsonResult.createJsonResult(-2, "存在对应的账单，不能回滚");
        }

        int retCode = vasOrderDao.rollbackVasOrderStatus(enterpriseId, username, orderId, remark);
        if (retCode > 0) {
            doSendAlert(enterpriseId, "服务订单(" + vasOrder.getOrderNo() + ")已回滚: " + remark, null,
                EntDepartment.DEPT_ADMINISTRATOR);
        }
        return JsonResult.createJsonResult(retCode);
    }

    @Override
    public void autoAlertVasOrderStatus() {
        final int enterpriseId = 5;
        SearchFlightOrderCriteria sc = new SearchFlightOrderCriteria();
        sc.setStatus(0);
        sc.setPageSize(1000);

        List<VasOrder> orders = vasOrderDao.searchVasOrders(enterpriseId, null, sc, true, null);

        //待处理状态的数量
        final int count0 = orders.size();

        //处理中
        sc.setStatus(1);
        orders = vasOrderDao.searchVasOrders(enterpriseId, null, sc, true, null);
        final int count1 = orders.size();

        if (count0 > 0 || count1 > 0) {
            doSendAlert(enterpriseId, "有服务订单需要处理(" + count0 + " 待处理, " + count1 + " 处理中).", null,
                EntDepartment.DEPT_TICKETING);
        }
    }

    @Override
    public void autoAlertInsuranceOrderStatus() {
        final int enterpriseId = 5;
        SearchFlightOrderCriteria sc = new SearchFlightOrderCriteria();
        sc.setStatus(0);
        sc.setPageSize(1000);

        List<VasOrder> orders = vasOrderDao.searchInsuranceOrders(enterpriseId, sc, null);

        //待处理状态的数量
        final int count0 = orders.size();

        //处理中
        sc.setStatus(1);
        orders = vasOrderDao.searchInsuranceOrders(enterpriseId, sc, null);
        final int count1 = orders.size();

        if (count0 > 0 || count1 > 0) {
            doSendAlert(enterpriseId, "有保险订单需要处理(" + count0 + " 待处理, " + count1 + " 处理中).", null,
                EntDepartment.DEPT_TICKETING);
        }
    }

    @Override
    public void checkVaasOrders(final int enterpriseId, final String username) {
        SearchFlightOrderCriteria sc = new SearchFlightOrderCriteria();
        sc.setPageSize(1000);
        sc.setOrderType(1);
        sc.setCustomerId(-1);

        //TODO 以下两次查询可以改进为一次 yfdai 2021-10-13
        //检查待处理
        sc.setStatus(TmsOrderConstant.ORDER_STATUS_WAITING);
        List<VasOrder> orders = vasOrderDao.searchVasOrders(enterpriseId, null, sc, true, null);
        checkVaasOrders(enterpriseId, username, orders);

        //检查处理中
        sc.setStatus(TmsOrderConstant.ORDER_STATUS_PROCESSING);
        orders = vasOrderDao.searchVasOrders(enterpriseId, null, sc, true, null);
//        logger.info("Vaas ORDER_STATUS_PROCESSING: " + orders.size());
        checkVaasOrders(enterpriseId, username, orders);
    }

    private void checkVaasOrders(final int enterpriseId, final String agentName, final List<VasOrder> orders) {
        for (VasOrder info : orders) {
            if (info.getStatus() == TmsOrderConstant.ORDER_STATUS_WAITING) {
                // 待处理的服务单
                //认领订单
                this.processVasOrder(enterpriseId, agentName, info.getId());

                if (info.getExternalOrderNo() != null
                    && info.getExternalOrderNo().trim().length() > 0) {
                    //校验订单状态
                    checkRemoteVaasOrder(enterpriseId, agentName, info);
                } else {
                    //通过接口提交订单
                    createRemoteVaasOrder(enterpriseId, agentName, info);
                }
            } else if (info.getStatus() == TmsOrderConstant.ORDER_STATUS_PROCESSING) {
                // 处理中的订单
                checkRemoteVaasOrder(enterpriseId, agentName, info);
            }
        }
    }

    private void checkRemoteVaasOrder(final int enterpriseId, final String agentName, final VasOrder info) {
      AirportService airportService = createAirportService(enterpriseId);
      VasOrderResponse response = airportService.getServiceOrder(info.getExternalOrderNo());

//      logger.info(JSON.toJSON(response));

      if (response == null) {
        return;
      }

      if (response.getErrorCode() != 0) {
        return;
      }

      final int newStatus = response.getData().getStatus();
      final int oldStatus = info.getStatus();

      if (oldStatus == newStatus) {
        return;
      }

      if (newStatus == TmsOrderConstant.ORDER_STATUS_CANCELED) {
        //TODO 如果该订单是现金付款，如何处理？
        int retCode = vasOrderDao
            .cancelVasOrder(enterpriseId, agentName, info.getId(), "接口订单已取消");
        if (retCode == 1) {
          String remark = "机场服务订单(" + info.getOrderNo() + ")已取消";
          doSendAlert(enterpriseId, remark, null, EntDepartment.DEPT_VAAS_SERVICE);
        }
      } else if (newStatus == TmsOrderConstant.ORDER_STATUS_PROCESSING) {
        //处理中
        vasOrderDao.processVasOrder(enterpriseId, agentName, info.getId(), "订单状态接口同步");
      } else if (newStatus == TmsOrderConstant.ORDER_STATUS_DONE) {
        for (cn.buk.api.vaas.dto.VasOrderPassengerDto psgDto : response.getData().getPassengers()) {
          if (psgDto.getSeatNo() != null && psgDto.getSeatNo().trim().length() > 0) {
            for (VasOrderPassenger psg : info.getPassengers()) {
              if (psg.getName().equalsIgnoreCase(psgDto.getName()) &&
                  !psgDto.getSeatNo().equalsIgnoreCase(psg.getSeatNo())
              ) {
                //保存座位号
                vasOrderDao.updateVasOrderPassengerSeatNo(enterpriseId, agentName,
                        info.getId(), psg.getId(), psg.getName(),
                        psgDto.getSeatNo());
                break;
              }
            }
          }
        }

        //检查是否已填写供应商和支出方式，如果没有，按照接口默认供应商自动设置
        if (info.getSupplier() == null) {
          //获取默认供应商
          ProductDefaultSupplier apiSupplier = enterpriseDao.searchSupplierByApiProduct(enterpriseId, PRODUCT_TYPE_VAAS);
          if (apiSupplier != null) {
            Supplier supplier = apiSupplier.getSupplier();
            if (supplier != null && supplier.getPaymentMethodId() >0) {
              updateVasOrderSupplier(enterpriseId, agentName, info.getId(), supplier.getId(), supplier.getPaymentMethodId());
            }
          }
        }

        JsonResult jsonResult = this
            .finishVasOrder(enterpriseId, agentName, info.getId(), "订单状态接口同步");

        if (!JsonResult.STATUS_OK.equalsIgnoreCase(jsonResult.getStatus())) {
          final String remark =
              "机场服务订单(" + info.getOrderNo() + ")状态同步失败，原因：" + jsonResult.getErrmsg();
          doSendAlert(enterpriseId, remark, null, EntDepartment.DEPT_VAAS_SERVICE);
        } else {
//          final String remark = "机场服务订单(" + info.getOrderNo() + ")处理完成。";
//          doSendAlert(enterpriseId, remark, null, EntDepartment.DEPT_VAAS_SERVICE);
          //TODO 发送短信给客户
          processOrderAirportName(info);

          for(VasOrderPassenger psg: info.getPassengers()) {
            String smsContent = generateVaasOrderSmsContent(enterpriseId, info, psg);
            SmsDetail smsDetail = SmsDetail.createSmsDetail(enterpriseId, agentName, psg.getMobile(), smsContent, info.getOrderNo());
            sendSms(smsDetail);
          }
        }
      }
    }

  private String generateVaasOrderSmsContent(int enterpriseId, VasOrder order, VasOrderPassenger psg) {
    final String companySign = doGetEntCfg(enterpriseId, EnterpriseConfig.API_SMS_COMPANY_SIGN);
    final String psgName = psg.getName();
    final String smsRouteInfo = SmsUtil.convertVaasOrder(order);
    final String seatNo = psg.getSeatNo();
    final String VAAS_ORDER_DONE_TEMPLATE = "%s尊敬的%s旅客：我们已为您预选了%s航班上预留座位%s的座位。温馨提示：如遇航司当天机型变动，则会影响您的预留座位。";


    return String
            .format(VAAS_ORDER_DONE_TEMPLATE, companySign, psgName, smsRouteInfo, seatNo);
  }

    /**
     * 创建订单（向机场服务系统提交订单）
     */
    private void createRemoteVaasOrder(int enterpriseId, String agentName, VasOrder info) {
        cn.buk.api.vaas.dto.VasOrderDto dto = new cn.buk.api.vaas.dto.VasOrderDto();
        dto.setProductCode(info.getProductCode());
        dto.setProductName(info.getProductName());

        for (VasOrderFlight flt : info.getFlights()) {
            VasOrderFlightDto flightDto = new VasOrderFlightDto();

            flightDto.getFlight().setDepartureAirport(flt.getFlight().getDepartureAirport());
            flightDto.getFlight().setArrivalAirport(flt.getFlight().getArrivalAirport());
            flightDto.getFlight().setFlightNo(flt.getFlight().getFlightNo());
            flightDto.getFlight().setDepartureDate(flt.getFlight().getDepartureDate());

            dto.getFlights().add(flightDto);
        }

        for (VasOrderPassenger psg : info.getPassengers()) {
            cn.buk.api.vaas.dto.VasOrderPassengerDto passengerDto = new cn.buk.api.vaas.dto.VasOrderPassengerDto();
            passengerDto.setName(psg.getName());
            passengerDto.setIdNo(psg.getIdNo());
            passengerDto.setIdType(psg.getIdType());
            passengerDto.setMobile(psg.getMobile());

            dto.getPassengers().add(passengerDto);
        }

        dto.setExternalOrderNo(info.getOrderNo());
        dto.setRemark(info.getRemark());

        AirportService airportService = createAirportService(enterpriseId);

        VasOrderCreateResponse response = airportService.createServiceOrder(dto);

        if (response != null) {
            if (response.getErrorCode() == 0) {
                //接口调用成功
                vasOrderDao.updateVaasOrderExternalOrderNo(enterpriseId, agentName, info.getId(),
                    response.getOrderNos());
            } else {
                final String remark = "机场服务订单(" + info.getOrderNo() + ")提交失败，原因：" + response.getErrorMsg();
                doSendAlert(enterpriseId, remark, null, EntDepartment.DEPT_ADMINISTRATOR);
                vasOrderDao.appendVasOrderLog(enterpriseId, agentName, info.getId(), remark);
            }
        }
    }

    /**
     * 取消接口订单
     * @return 0-操作成功，其它-失败代码
     */
    private int cancelRemoteVaasOrder(final int enterpriseId, final String username, final VasOrder vasOrder, final String reason) {
        AirportService airportService = createAirportService(enterpriseId);

        BaseResponse response = airportService.cancelServiceOrder(vasOrder.getExternalOrderNo(), reason);

        vasOrderDao.appendVasOrderLog(enterpriseId, username, vasOrder.getId(), "取消接口订单：" + response.getErrorCode() + ", " + response.getErrorMsg());

        return response.getErrorCode();
    }
}
